package com.mall.order.biz.mq;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.nio.charset.Charset;

/**
 * @Classname DelayOrderCancelProducer
 * @Description NULL
 * @Date 2021/5/26 14:04
 * @Created by virus
 */
@Slf4j
@Component
public class DelayOrderCancelProducer {

    public static final String ORDER_DELAY_TOPIC = "delay_cancel_order";

    DefaultMQProducer defaultMQProducer;

    @PostConstruct
    public void init() {
        defaultMQProducer = new DefaultMQProducer(ORDER_DELAY_TOPIC + "_producer");
        defaultMQProducer.setNamesrvAddr("127.0.0.1:9876");
        try {
            defaultMQProducer.start();
        } catch (MQClientException e) {
            e.printStackTrace();
        }
    }

    public boolean sendDelayCancelMessage(String orderId) {
        log.info("DelayOrderCancelProducer is ready to send message");
        Message message = new Message();
        message.setTopic(ORDER_DELAY_TOPIC);
        message.setBody(orderId.getBytes(Charset.forName("utf-8")));
        message.setDelayTimeLevel(16);
        SendResult send = null;
        try {
            send = defaultMQProducer.send(message);
        } catch (MQClientException | RemotingException | MQBrokerException | InterruptedException e) {
            e.printStackTrace();
        }
        if (send != null && send.getSendStatus().equals(SendStatus.SEND_OK)) {
            log.info("DelayOrderCancelProducer sent message successfully");
            return true;
        }
        log.error("DelayOrderCancelProducer failed to send message");
        return false;
    }
}
